//
//  MainViewController.m
//  Ezi2u
//
//  Created by mac on 16/9/20.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MainViewController.h"
#import "LoginViewController.h"
#import "NSString+MD5.h"
#import "NSString+token.h"
#import "NSString+URL.h"
#import <SVProgressHUD.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "ScannerViewController.h"
#import "NavigationViewController.h"
#import "WXApi.h"

@interface MainViewController ()

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.loginType = NoneActionType;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_USERNAME] && [[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_PASSWORD]){
    [self loginActionWithTag:ActionTypeLogin];
    }
    self.navigationController.navigationBarHidden = YES;
}
-(void)wechatLoginInWebView{
    self.loginType = ActionTypeWeChatLogin;
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:WX_USERINFOR];
    NSString *url = [NSString stringWithFormat:@"%@iosapp/index.php?mod=app&act=wechat_login&nickname=%@&openid=%@",API_HOST,[dic objectForKey:@"nickname"],[dic objectForKey:@"openid"]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [self.mainWebView loadRequest:request];
    [SVProgressHUD showWithStatus:@"Loading..."];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_PASSWORD]);
    if (self.loginType == NoneActionType && ![[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_PASSWORD]) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        LoginViewController  *login =[storyBoard  instantiateViewControllerWithIdentifier:@"loginViewController"];
        login.A_Delegate = self;
        [self presentViewController:login animated:YES completion:^{
            NSLog(@"present!");
        }];
    }
}

#pragma mark -UIWebViewDelegate-
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL *url = [request URL];
     NSLog(@"request_url==>%@",url);
    if ([[url scheme] isEqualToString:@"submit_app"]) {
        
    }
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    NSLog(@"webViewDidStartLoad!");
    [SVProgressHUD showWithStatus:@"Loading..."];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"webViewDidFinishLoad!");
    [SVProgressHUD dismiss];
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    //保存用户名密码
    context[@"iossaveuser"] = ^{
        
        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"iossaveuser（）--js传递参数：%@", obj);
        }
        NSString *username = [NSString stringWithFormat:@"%@",[arg objectAtIndex:0]];
        NSString *password = [NSString stringWithFormat:@"%@",[arg objectAtIndex:1]];
        //存储用户名和密码
        [[NSUserDefaults standardUserDefaults] setObject:username forKey:EZI2U_USERNAME];
        NSLog(@"存储的用户名：%@",[[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_USERNAME]);
        [[NSUserDefaults standardUserDefaults] setObject:password forKey:EZI2U_PASSWORD];
        NSLog(@"存储的密码：%@",[[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_PASSWORD]);
    };
    
    //清除用户名密码
    context[@"iosclearpassword"] = ^{
        
        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"iosclearpassword（）--js传递参数：%@", obj);
        }
        //清空存储的密码
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:EZI2U_PASSWORD];
        
        NSLog(@"存储的用户名：%@",[[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_USERNAME]);
        NSLog(@"存储的密码：%@",[[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_PASSWORD]);
    };
    
    //扫二维码
    context[@"ioscallqrcodescan"] = ^{
        
        ScannerViewController  *scan = [[ScannerViewController alloc]initWithNibName:@"ScannerViewController" bundle:nil];
        [self presentViewController:scan animated:YES completion:^{
            [scan initQRCodeBlock:^(NSString *qrcode){
                NSLog(@"qrcode=%@",qrcode);
                NSString *jsCallBack = [NSString stringWithFormat:@"callOCRback('%@')",qrcode];
                [self performSelectorOnMainThread:@selector(callJs:) withObject:jsCallBack waitUntilDone:YES];
            }];
        }];
    };
    //微信分享
    context[@"iosWXSceneSession"] = ^{
        
        NSArray *arg = [JSContext currentArguments];
        NSString *url = [NSString stringWithFormat:@"%@",[arg objectAtIndex:0]];
        NSString *title = [NSString stringWithFormat:@"%@",[arg objectAtIndex:1]];
        NSString *desc = [NSString stringWithFormat:@"%@",[arg objectAtIndex:2]];
        if (![WXApi isWXAppInstalled]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"请先安装微信客户端！" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
            [alert show];
            return;
        }
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;
        message.description = desc;
        [message setThumbImage:[UIImage imageNamed:@"shareIcon"]];
        
        WXWebpageObject *webpageObject = [WXWebpageObject object];
        webpageObject.webpageUrl = url;
        message.mediaObject = webpageObject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;
        [WXApi sendReq:req];

    };
    //微信朋友圈分享
    context[@"iosWXSceneTimeline"] = ^{
        
        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"iosWXSceneSession（）--js传递参数：%@", obj);
        }
        if (![WXApi isWXAppInstalled]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"请先安装微信客户端！" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
            [alert show];
            return;
        }
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = [NSString stringWithFormat:@"%@",[arg objectAtIndex:1]];
        message.description = [NSString stringWithFormat:@"%@",[arg objectAtIndex:2]];
        [message setThumbImage:[UIImage imageNamed:@"shareIcon"]];
        
        WXWebpageObject *webpageObject = [WXWebpageObject object];
        webpageObject.webpageUrl = [NSString stringWithFormat:@"%@",[arg objectAtIndex:0]];
        message.mediaObject = webpageObject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneTimeline;
        [WXApi sendReq:req];

    };
    //facebook分享
    context[@"iosFaceBookShare"] = ^{
        
        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"iosFaceBookShare（）--js传递参数：%@", obj);
        }
        NSString *url = [NSString stringWithFormat:@"%@",[arg objectAtIndex:0]];
        NSString *title = [NSString stringWithFormat:@"%@",[arg objectAtIndex:1]];
        NSString *imgUrl = [NSString stringWithFormat:@"%@",[arg objectAtIndex:2]];
        FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
        content.contentURL = [NSURL URLWithString:url];
        content.contentTitle = title;
        content.imageURL = [NSURL URLWithString:imgUrl];
        [FBSDKShareDialog showFromViewController:self
                                     withContent:content
                                        delegate:self];
    };
    
    //facebook分享
    context[@"iosalertmap"] = ^{
        
        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"iosalertmap（）--js传递参数：%@", obj);
        }
        NSString *url = [NSString stringWithFormat:@"%@",[arg objectAtIndex:0]];
        url = [url URLEncodedString];
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        NavigationViewController  *nav =[storyBoard  instantiateViewControllerWithIdentifier:@"navigationViewController"];
        [self presentViewController:nav animated:YES completion:^{
            NSLog(@"present!");
        }];
        [nav navigateWithUrl:url];

    };
}
-(void)callJs:(NSString*)qrcode{
    [self.mainWebView stringByEvaluatingJavaScriptFromString:qrcode];
}
#pragma mark -LoginDelegate-
-(void)loginActionWithTag:(LoginActionType)type{
    self.loginType = type;
    NSString *url;
    NSDictionary *dic;
    if (type == ActionTypeWeChatLogin) {
        dic = [[NSUserDefaults standardUserDefaults] objectForKey:WX_USERINFOR];
    }else if (type == ActionTypeFacebookLogin){
        dic = [[NSUserDefaults standardUserDefaults] objectForKey:FB_USERINFOR];
    }else{
        
    }
    switch (type) {
        case 0:
            url = [NSString stringWithFormat:@"%@iosapp/index.php?mod=app&act=login&token=%@&username=%@&password=%@",API_HOST,[NSString MD5:[NSString token]],[[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_USERNAME],[NSString MD5:[[NSUserDefaults standardUserDefaults] objectForKey:EZI2U_PASSWORD]]];
            url = [url URLEncodedString];
            break;
        case 1:
            url = [NSString stringWithFormat:@"%@iosapp/index.php?mod=app&act=facebook_login&token=%@&name=%@&userid=%@",API_HOST,[NSString MD5:[NSString token]],[dic objectForKey:@"name"],[dic objectForKey:@"userid"]];
            url = [url URLEncodedString];
            break;
        case 2:
            url = [NSString stringWithFormat:@"%@iosapp/index.php?mod=app&act=wechat_login&token=%@&nickname=%@&openid=%@",API_HOST,[NSString MD5:[NSString token]],[dic objectForKey:@"nickname"],[dic objectForKey:@"openid"]];
            url = [url URLEncodedString];
            break;
        case 3:
            url = [NSString stringWithFormat:@"%@%@",API_HOST,@"iosapp/index.php?mod=register"];
            break;
        case 4:
            url = [NSString stringWithFormat:@"%@%@",API_HOST,@"iosapp/index.php?mod=register"];
            break;
        case 5:
            url = [NSString stringWithFormat:@"%@%@",API_HOST,@"iosapp/index.php"];
        default:
            break;
    }
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [self.mainWebView loadRequest:request];
    [SVProgressHUD showWithStatus:@"Loading..."];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
}

#pragma mark -FBSDKSharingDelegate-
- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results{
    NSLog(@"share completed!");
    
}
- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error{
    NSLog(@"share failed!");
}
- (void)sharerDidCancel:(id<FBSDKSharing>)sharer{
    NSLog(@"share canceled!");
}
#pragma mark -StatusBarHidden-
-(BOOL)prefersStatusBarHidden{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
